package org.dreamfly.core.action;

import org.dreamfly.core.bean.SzAuthorities;
import org.dreamfly.core.bean.SzUser;
import org.dreamfly.core.bean.SzUsers;
import org.dreamfly.core.bean.User;
import org.dreamfly.core.service.UserService;
import org.dreamfly.core.util.HTMLInputFilter;
import org.springframework.security.context.SecurityContextHolder;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by IntelliJ IDEA.
 * User: gin
 * Date: 8/12/11
 * Time: 8:12 AM
 * To change this template use File | Settings | File Templates.
 */
public class UserAction extends BaseAction {
    private UserService userService;
    private SzUsers user;
    private List<SzUsers> userList;
    private Long id;
    private String server;
    private String oldPassword;
    private String username;
    private String confirmPass;
    private HTMLInputFilter filter;
    private final String ROLE_USER = "ROLE_USER";
    private Set<SzAuthorities> authoritySet = new HashSet<SzAuthorities>();
    private List<String> authorList = new ArrayList<String>();
    private Lock userLock = new ReentrantLock();

    public void register() {
        user.setIsNew(true);
        user.setServer(server);
        user.setIsAdmin(false);
        addDefaultRole();
        user.setSzAuthoritieses(authoritySet);
        userLock.lock();
        if (null == userService.findUserByName(user.getUsername()) && user.getPassword().equals(confirmPass)
                && judgeUsername(user.getUsername()) && (user.getPassword().trim().length() >= 6)) {
            userService.addUser(user);
        }
        try {
            if (null == user.getId()) {
                response.getWriter().print("false");
            } else {
                response.getWriter().print("true");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            userLock.unlock();
        }
    }

    private void addDefaultRole() {
        SzAuthorities authorities = new SzAuthorities();
        authorities.setAuthor("ROLE_USER");
        authorities.setSzUsers(user);
        authoritySet.add(authorities);
    }

    public String getOldUserList() {
        userList = userService.findUserList();
        return SUCCESS;
    }

    public String getNewUserList() {
        userList = userService.findNewUserList();
        return SUCCESS;
    }

    public void confirmUser() {
        try {
            if (null == userService.findUserByName(username)) {
                response.getWriter().print("true");
            } else {
                response.getWriter().print("false");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void confirmPassword(){
        user = userService.findUser(id);
        try {
            if (oldPassword.equals(user.getPassword())) {
                response.getWriter().print("true");
            } else {
                response.getWriter().print("false");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void modifyUser(){
        SzUsers szUser = userService.findUser(id);
        if(oldPassword.equals(szUser.getPassword()) && user.getPassword().equals(confirmPass)
                && isUsernameModifyable(id, user.getUsername())){
            szUser.setUsername(user.getUsername());
            szUser.setPassword(user.getPassword());
            szUser.setAddr(user.getAddr());
            szUser.setEmail(user.getEmail());
            szUser.setName(user.getName());
            szUser.setTele(user.getTele());
            szUser.setSex(user.getSex());
            userService.updateUserInfo(szUser);
            try {
                response.getWriter().print("true");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            try {
                response.getWriter().print("false");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private boolean isUsernameModifyable(Long id, String username){
        SzUsers user = userService.findUserByName(username);
        if(null == user || id.equals(user.getId())){
            return true;
        }else {
            return false;
        }
    }

    public String getUserFullInfo(){
        Long id = ((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId();
        user = userService.findUser(id);
        if(null != user){
            return SUCCESS;
        } else {
            return INPUT;
        }
    }

    public void getUserInfo() {
        user = userService.findUser(id);
        StringBuilder authorities = listAuthorities();
        try {
            response.getWriter().write(authorities.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private StringBuilder listAuthorities() {
        Set<SzAuthorities> authoritySet;
        StringBuilder authorities = new StringBuilder();
        authoritySet = user.getSzAuthoritieses();
        for (SzAuthorities authority : authoritySet) {

            if (!ROLE_USER.equals(authority.getAuthor())) {
                authorities.append(authority.getAuthor());
                authorities.append(":");
            }
        }
        if (authorities.length() > 0) {
            authorities.deleteCharAt(authorities.length() - 1);
        }
        return authorities;
    }

    /*public void assignAuthority() {
        user = userService.findUser(id);
        user.setIsNew(false);
        addDefaultRole();
        for(SzAuthorities authority : authoritySet){
            authority.setSzUsers(user);
        }
        user.setSzAuthoritieses(authoritySet);
        userService.updateUser(user);
        try {
            response.getWriter().print("true");
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }*/

    public void modifyAuthority() {
        user = userService.findUser(id);
        //userService.deleteUser(user);
        user.setIsNew(false);
        addDefaultRole();
        for (String author : authorList) {
            SzAuthorities authorities = new SzAuthorities();
            authorities.setAuthor(author);
            authorities.setSzUsers(user);
            authoritySet.add(authorities);
        }
        userService.clearUserAuthorities(user);
        user.setSzAuthoritieses(authoritySet);
        userService.updateUser(user);
        try {
            response.getWriter().print("true");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private boolean judgeUsername(String username) {
        if (null == username || "".equals(username.trim())) {
            return false;
        } else {
            return countStringLength(username) <= 10;
        }
    }

    private int countStringLength(String username) {
        int length=0;
        char[] charArray = username.toCharArray();
        for (int i = 0; i < charArray.length; i++) {
            if ((charArray[i] >= 0x4e00) && (charArray[i] <= 0x9fbb)) {
                length += 2;
            }else {
                length +=1;
            }
        }
        return length;
    }

    public void validateRegister() {

    }

    public String getConfirmPass() {
        return confirmPass;
    }

    public void setConfirmPass(String confirmPass) {
        this.confirmPass = confirmPass;
    }

    public void setServer(String server) {
        this.server = server;
    }

    public SzUsers getUser() {
        return user;
    }

    public void setUser(SzUsers user) {
        this.user = user;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public List<SzUsers> getUserList() {
        return userList;
    }

    /*private String initialPageInfo() {
        if (userList.isEmpty()) {
            return INPUT;
        } else {
            user = userList.get(0);
            return SUCCESS;
        }
    }*/

    public void setUsername(String username) {
        this.username = username;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Set<SzAuthorities> getAuthoritySet() {
        return authoritySet;
    }

    public void setAuthoritySet(Set<SzAuthorities> authoritySet) {
        this.authoritySet = authoritySet;
    }

    public void setAuthorList(List<String> authorList) {
        this.authorList = authorList;
    }

    public void setOldPassword(String oldPassword) {
        this.oldPassword = oldPassword;
    }
}
